
var GRAMMAR;

function initialise(gram) {
    GRAMMAR = gram;
    var languagelist = document.getElementById("language");
    languagelist.innerHTML = "";
    for (var lang in GRAMMAR.concretes) {
	languagelist.innerHTML += "<option>" + lang + "</option>";
    }
        
    var examplelist = document.getElementById("example");
    examplelist.innerHTML = "";
    for (var ex in examples) {
	examplelist.innerHTML += "<option>" + ex + "</option>";
        GRAMMAR.abstract.typecheck(examples[ex]);
    }

    performCommand();
}

function performCommand() {
    var tree = examples[document.getElementById("example").value];
    var lang = document.getElementById("language").value;
    var lin = GRAMMAR.linearise(lang, tree);
    document.getElementById("linearisation").innerHTML = linAsHtml(lin);
    document.getElementById("linsource").innerHTML = "var lin = " + objectAsJavascript(lin);
    document.getElementById("treesource").innerHTML = "var tree = " + objectAsJavascript(tree);
    document.getElementById("indentedtree").innerHTML = treeAsHtml(tree);
}

function linAsHtml(lin) {
    var result = lin.map(function(w){
        return "<em>" + w.word + "</em><sub><b>" + w.node + "</b></sub>";
    });
    return result.join(" &nbsp; ");
}

function treeAsHtml(tree) {
    if (tree instanceof Object && (tree.node || tree.type)) {
        var children = tree.children.map(function(child){
            return treeAsHtml(child);
        });
        children = children.join("</ul><ul>");
        if (children) {
            children = "<ul>" + children + "</ul>";
        }
        return "<li><em>" + (tree.node || "?") + "</em> : " + (tree.type || "?") + children + "</li>";
    } else {
        return "<pre>" + objectAsJavascript(tree) + "</pre>";
    }
}

function objectAsJavascript(obj) {
    if (obj == null) {
	return "" + obj;
    } else if (obj instanceof Array) {
	var result = obj.map(function(o){
	    return objectAsJavascript(o);
	});
	return "[" + result.join(", ") + "]";
    } else if (obj instanceof Object) {
	var result = [];
	for (var key in obj) {
	    result.push(key + ": " + objectAsJavascript(obj[key]));
	}
	return "{" + result.join(", ") + "}";
    } else if (typeof obj == "string") {
	return '"' + obj + '"'
    } else {
	return "" + obj;
    }
}

